import * as Koa from 'koa';
import { delUserTemp, updateUserTemp, searchUserTemp } from "../entity/user-temp";
import { joinDefaultFields } from '../utils';
const dayjs = require("dayjs");
// TODO：commonjs 模式下引用 esmodule 模块
let nanoid: any = null;
(async () => {
  nanoid = (await eval("import('nanoid')")).nanoid;
})();

const errorMsg = `服务器错误：${'user-temp'}`;
const successMsg = `成功：${'user-temp'}`;

export default class UserTempService {
  /**
   * 删除
   * @param ctx 
   */
  delUserTemp = async (ctx: Koa.Context) => {
    try {
      const { utid } = ctx.request.body;
      if (!utid || !utid.length) return ctx.fail(null, "tuid不能为空", -1);
      const tuids = Array.isArray(utid)? utid : [utid];
      let condition = `utid IN (${tuids.map((i) => `"${i}"`).join(",")})`;
      const result: any =  !!tuids.length && await delUserTemp(ctx, { condition });
      if (!result) {
        ctx.fail(null, result.msg || errorMsg, -1);
      } else if (!result.success) {
        ctx.fail(null, result.msg || errorMsg, -1);
      } else {
        ctx.success(null, successMsg);
      }
    } catch (error) {
      ctx.fail(null, errorMsg, -1);
    }
  };

  /**
   * 修改
   * @param ctx 
   */
  updateUserTemp = async (ctx: Koa.Context) => {
    ctx.success(null, successMsg);
  };

  /**
   * 查询
   * @param ctx 
   */
  searchUserTemp = async (ctx: Koa.Context) => {
    try {
      const params = ctx.request.body;
      const { utid, uid } = params || {}; // 查询条件
      // 相等的条件
      let condition = "";
      let equals: string | string[] = [];
      uid && (equals.push(` uid = "${uid}"`));
      utid && (equals.push(` utid = "${utid}"`));
      equals = equals.join(" AND");
      equals && (condition += `WHERE ${equals}`);
      const result: any = await searchUserTemp(ctx, { condition });
      if (!result) {
        ctx.fail(null, result.msg || errorMsg, -1);
      } else if (!result.success) {
        ctx.fail(null, result.msg || errorMsg, -1);
      } else {
        ctx.success({
          list: result.data || [],
        }, successMsg);
      }
    } catch (error) {
      ctx.fail(null, errorMsg, -1);
    }
  };
}
